import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/screens/order/order_details_screen.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '/data/model/response/order_model.dart';
import '/helper/responsive_helper.dart';
import '/helper/route_helper.dart';
import 'cancellation_reason_dialog.dart';

class OrderListWidget extends StatelessWidget {
  const OrderListWidget({
    Key? key,
    required this.orderList,
    required this.paginate,
    required this.orderController,
  }) : super(key: key);

  final List<OrderModel> orderList;
  final bool paginate;
  final OrderController orderController;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListView.builder(
          padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
          itemCount: orderList.length + 1,
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            if (index != orderList.length) {
              return InkWell(
                onTap: () {
                  Get.toNamed(
                    RouteHelper.getOrderDetailsRoute(orderList[index].id!),
                    arguments: OrderDetailsScreen(
                      orderId: orderList[index].id!,
                      orderModel: orderList[index],
                      index: index,
                    ),
                  );
                },
                child: Container(
                  padding: ResponsiveHelper.isDesktop(context)
                      ? EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL)
                      : null,
                  margin: ResponsiveHelper.isDesktop(context)
                      ? EdgeInsets.only(bottom: Dimensions.PADDING_SIZE_SMALL)
                      : null,
                  decoration: ResponsiveHelper.isDesktop(context)
                      ? BoxDecoration(
                          color: Theme.of(context).cardColor,
                          borderRadius:
                              BorderRadius.circular(Dimensions.RADIUS_SMALL),
                          boxShadow: [
                            BoxShadow(
                                color: Colors.grey[Get.isDarkMode ? 700 : 300]!,
                                blurRadius: 5,
                                spreadRadius: 1)
                          ],
                        )
                      : null,
                  child: OrderItemWidget(
                      orderList: orderList,
                      orderController: orderController,
                      index: index),
                ),
              );
            } else {
              return SizedBox(
                height: 10.h,
              );
            }
          },
        ),
        paginate
            ? Padding(
                padding: EdgeInsets.only(bottom: 12.h),
                child: Center(
                  child: CircularProgressIndicator.adaptive(
                    backgroundColor: Theme.of(context).colorScheme.secondary,
                  ),
                ),
              )
            : SizedBox(),
      ],
    );
  }
}

class OrderItemWidget extends StatefulWidget {
  const OrderItemWidget({
    Key? key,
    required this.orderList,
    required this.orderController,
    required this.index,
  }) : super(key: key);

  final List<OrderModel> orderList;
  final OrderController orderController;
  final int index;

  @override
  State<OrderItemWidget> createState() => _OrderItemWidgetState();
}

class _OrderItemWidgetState extends State<OrderItemWidget> {
  @override
  void initState() {
    widget.orderController.initializeTimer(widget.orderList[widget.index],
        widget.orderList[widget.index].remainingTime ?? 0, widget.index);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OrderController>(
      init: widget.orderController,
      builder: (controller) {
        return Column(children: [
          Row(children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
              child: CustomImage(
                image: widget.orderList[widget.index].restaurant!.logo!,
                height: 60,
                width: 60,
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${widget.orderList[widget.index].restaurant?.name}',
                      style:
                          sfMedium.copyWith(fontSize: Dimensions.fontSizeSmall),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
                    Text(
                      DateConverter.dateTimeStringToDateTime(
                        widget.orderList[widget.index].createdAt ?? '',
                      ),
                      style: sfRegular.copyWith(
                        color: Theme.of(context).disabledColor,
                        fontSize: Dimensions.fontSizeSmall,
                      ),
                    ),
                    SizedBox(height: 5),
                    widget.orderList[widget.index].bonusPoint! > 0
                        ? Text(
                            'bonus_message_short'.trParams({
                              'point': widget.orderList[widget.index].bonusPoint
                                  .toString()
                            }),
                            style: TextStyle(
                              fontSize: Dimensions.fontSizeSmall,
                              color: Theme.of(context).colorScheme.secondary,
                            ),
                          )
                        : SizedBox()
                  ],
                ),
              ),
            ),
            SizedBox(width: Dimensions.PADDING_SIZE_SMALL),
            Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
              widget.orderList[widget.index].orderStatus == "canceled"
                  ? Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: Dimensions.PADDING_SIZE_SMALL,
                          vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            Theme.of(context).colorScheme.primary,
                            Theme.of(context).colorScheme.secondary
                          ],
                          tileMode: TileMode.mirror,
                        ),
                        borderRadius:
                            BorderRadius.circular(Dimensions.RADIUS_SMALL),
                      ),
                      child: Text(
                          widget.orderList[widget.index].orderStatus?.tr ?? '',
                          style: sfMedium.copyWith(
                            fontSize: Dimensions.fontSizeExtraSmall,
                            color: Theme.of(context).cardColor,
                          )),
                    )
                  : SizedBox(),
              SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
              [
                "pending",
                "accepted",
                "processing",
                "handover",
                "picked_up",
                "confirmed",
                "driver_arrived"
              ].contains(widget.orderList[widget.index].orderStatus)
                  ? InkWell(
                      onTap: () => Get.toNamed(
                          RouteHelper.getOrderTrackingRoute(
                              widget.orderList[widget.index].id!, false)),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: Dimensions.PADDING_SIZE_SMALL,
                            vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.circular(Dimensions.RADIUS_SMALL),
                            border: Border.all(
                              width: 1,
                              color: Theme.of(context).colorScheme.secondary,
                            )),
                        child: Row(children: [
                          Image.asset(Images.tracking,
                              height: 15,
                              width: 15,
                              color: Theme.of(context).colorScheme.secondary),
                          SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                          Text('track_order'.tr,
                              style: sfMedium.copyWith(
                                fontSize: Dimensions.fontSizeExtraSmall,
                                color: Theme.of(context).colorScheme.secondary,
                              )),
                        ]),
                      ),
                    )
                  : Text(
                      '${widget.orderList[widget.index].detailsCount} ${widget.orderList[widget.index].detailsCount! > 1 ? 'items'.tr : 'item'.tr}',
                      style: sfRegular.copyWith(
                          fontSize: Dimensions.fontSizeExtraSmall),
                    ),
              SizedBox(
                height: 0.6.h,
              ),
              [
                "pending",
                "confirmed",
                "accepted",
                "processing",
                "handover",
                "driver_arrived"
              ].contains(widget.orderList[widget.index].orderStatus)
                  ? InkWell(
                      onTap: () {
                        controller.getTimerText(widget.index) != '0:00'
                            ? showModalBottomSheet<dynamic>(
                                isScrollControlled: true,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(
                                      Dimensions.RADIUS_EXTRA_LARGE),
                                ),
                                context: context,
                                builder: (BuildContext bc) {
                                  return Wrap(children: <Widget>[
                                    CancellationDialog(
                                      orderId:
                                          widget.orderList[widget.index].id,
                                      orderController: widget.orderController,
                                      orderIndex: widget.index,
                                      fromOrderList: true,
                                    ),
                                  ]);
                                })
                            : showAlertDialog(context);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: Dimensions.PADDING_SIZE_SMALL,
                            vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.circular(Dimensions.RADIUS_SMALL),
                            border: Border.all(
                                color: Theme.of(context).disabledColor)),
                        child: Row(children: [
                          Image.asset(Images.cancelOrder,
                              height: 13,
                              width: 13,
                              color: Theme.of(context).disabledColor),
                          SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                          Text(
                              controller.getTimerText(widget.index) == '0:00'
                                  ? 'cancel_order'.tr
                                  : '${'cancel'.tr} (${controller.getTimerText(widget.index)})',
                              style: sfMedium.copyWith(
                                  fontSize: 9.3,
                                  color: Theme.of(context).disabledColor)),
                        ]),
                      ),
                    )
                  : SizedBox(),
            ]),
          ]),
          (widget.index == widget.orderList.length - 1 ||
                  ResponsiveHelper.isDesktop(context))
              ? SizedBox()
              : Padding(
                  padding: EdgeInsets.only(left: 70),
                  child: Divider(
                    color: Theme.of(context).disabledColor,
                    height: Dimensions.PADDING_SIZE_LARGE,
                  ),
                ),
        ]);
      },
    );
  }

  void showAlertDialog(BuildContext context) {
    AlertDialog alert3 = AlertDialog(
      scrollable: true,
      backgroundColor: Theme.of(context).cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(Dimensions.RADIUS_EXTRA_LARGE),
      ),
      title: Center(
          child: Column(
        children: [
          Icon(
            Icons.info,
            size: 50,
            color: Theme.of(context).primaryColor,
          )
        ],
      )),
      content: Container(
          width: 60.w,
          height: 7.h,
          padding: EdgeInsets.zero,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius:
                BorderRadius.circular(Dimensions.PADDING_SIZE_EXTRA_LARGE),
          ),
          child: Center(
              child: Text('cancel_time_over'.tr,
                  style: sfRegular.copyWith(fontSize: Dimensions.fontSizeLarge),
                  textAlign: TextAlign.center,
                  softWrap: true,
                  maxLines: 4))),
    );
    Get.dialog(alert3, barrierDismissible: true);
  }
}
